﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class joinGroup : System.Web.UI.Page
{
    private string userID;      //用于存放从Cookie中得到的userID，在Page_Load函数中被赋值
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            requestlistUl.InnerHtml = "";
            grouplistUl.InnerHtml = "";
        }

        //验证是否登录
        if (Request.Cookies["userID"] == null)
        {
            Response.Redirect("notLogin.html", true);
            return;
        }
        else
        {
            //获取已登录用户信息
            userID = Request.Cookies["userID"].Value;

            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectionstring"];
            using (SqlConnection dataBaseConnection = new SqlConnection(settings.ConnectionString))
            {
                dataBaseConnection.Open();
                //获取待处理的请求列表
                string queryString = "SELECT username, GroupName, RequestList.GroupID, RequestList.userID " +
                                     "FROM users, GroupInfo, RequestList " +
                                     "WHERE CreatedBy = @CreatedBy and GroupInfo.GroupID = RequestList.GroupID and RequestList.userID = users.userID";
                SqlCommand command = new SqlCommand(queryString, dataBaseConnection);
                SqlParameter CreatedByParameter = new SqlParameter("@CreatedBy", userID);
                command.Parameters.Add(CreatedByParameter);
                SqlDataReader reader;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception exception)
                {
                    Response.Redirect("DBError.aspx?error_msg=" + exception.Message.Replace(' ', '-') + "-AFTER-QUERY-OF-REQUEST", true);
                    return;
                }

                if (!reader.HasRows)
                {
                    requestlistUl.InnerHtml = "<p>暂时没有需要您处理的请求</p>";
                }
                else
                {
                    while (reader.Read())
                    {
                        //todo 这里的处理可能需要更改
                        requestlistUl.InnerHtml += "<li>" + reader["username"] + "申请加入您的小组" + reader["GroupName"] + "<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;<a href=\"processRequest.aspx?userID=" + reader["userID"] + "&groupID=" + reader["GroupID"] + "&accepted=1\"><img src=\"images/accepted.png\"></a>  <a href=\"processRequest.aspx?userID=" + reader["userID"] + "&groupID=" + reader["GroupID"] + "&accepted=0\"><img src=\"images/denied.png\"></a></li>";
                    }
                }
                reader.Close();


                //获取该用户加入的小组列表
                queryString = "SELECT GroupIDs " +
                              "FROM users " +
                              "WHERE userID = @userID";
                command.CommandText = queryString;
                command.Parameters.Clear();
                SqlParameter userIDParameter = new SqlParameter("@userID", userID);
                command.Parameters.Add(userIDParameter);
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception exception)
                {
                    Response.Redirect("DBError.aspx?error_msg=" + exception.Message.Replace(' ', '-'), true);
                    return;
                }

                reader.Read();
                string[] groups = reader["GroupIDs"].ToString().Split('&');
                reader.Close();

                if (groups[0] == string.Empty)
                {
                    grouplistUl.InnerHtml = "您还没有加入任何小组";
                }
                else
                {
                    int groupNum = groups.Length;
                    for (int i = 0; i < groupNum; i++)
                    {
                        if (groups[i] != string.Empty)
                        {
                            queryString = "SELECT GroupName " +
                                          "FROM GroupInfo " +
                                          "WHERE GroupID = @GroupID";
                            command.CommandText = queryString;
                            command.Parameters.Clear();
                            SqlParameter GroupIDParameter = new SqlParameter("@GroupID", groups[i]);
                            command.Parameters.Add(GroupIDParameter);
                            try
                            {
                                reader = command.ExecuteReader();
                            }
                            catch (Exception exception)
                            {
                                Response.Redirect("DBError.aspx?error_msg=" + exception.Message.Replace(' ', '-'), true);
                                return;
                            }

                            reader.Read();
                            string groupName = reader["GroupName"].ToString();
                            reader.Close();
                            grouplistUl.InnerHtml += "<li><a href=\"groupIndex.aspx?groupID=" + groups[i] + "&groupName=" + groupName + "\">" + groupName + "</a></li>";
                        }
                    }
                }
                dataBaseConnection.Close();
            }
        }
    }
    protected void submit_Click(object sender, EventArgs e)
    {
        string groupName_worked = groupName.Text.Trim();

        if (groupName_worked == string.Empty)
        {
            notification.InnerHtml = "请填写小组名称";
            return;
        }
        else
        {
            //填写了工作组名称，依次检查是否存在该小组、是否有重复申请、是否已经加入，然后加入请求列表
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectionString"];
            using (SqlConnection dataBaseConnection = new SqlConnection(settings.ConnectionString))
            {
                dataBaseConnection.Open();

                //检查小组是否存在
                string queryString = "SELECT GroupID " +
                                     "FROM GroupInfo " +
                                     "WHERE GroupName = @GroupName";
                SqlCommand command = new SqlCommand(queryString, dataBaseConnection);
                SqlParameter GroupNameParameter = new SqlParameter("@GroupName", groupName_worked);
                command.Parameters.Add(GroupNameParameter);
                SqlDataReader reader;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception exception)
                {
                    notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER EXISTING CHECK<br>" + exception.Message;
                    return;
                }

                if (!reader.HasRows)
                {
                    notification.InnerHtml = "您所填写的工作组并不存在，请核对后重新填写";
                    return;
                }
                else
                {
                    //存在工作组，检查是否有重复申请、是否已经加入，然后加入请求列表
                    reader.Read();
                    string groupID = reader["GroupID"].ToString();
                    reader.Close();

                    //检查是否有重复申请
                    queryString = "SELECT * " +
                                  "FROM RequestList " +
                                  "WHERE GroupID = @GroupID AND userID = @userID";
                    command.CommandText = queryString;
                    command.Parameters.Clear();
                    SqlParameter GroupIDParameter = new SqlParameter("@GroupID", groupID);
                    SqlParameter userIDParameter = new SqlParameter("@userID", userID);
                    command.Parameters.AddRange(new SqlParameter[]{GroupIDParameter, userIDParameter});
                    try
                    {
                        reader = command.ExecuteReader();
                    }
                    catch (Exception exception)
                    {
                        notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER DUPLICATE CHECK<br>" + exception.Message;
                        return;
                    }

                    if (reader.HasRows)
                    {
                        //存在重复申请
                        notification.InnerHtml = "您曾经提交过申请，而且小组创建者还没有处理您的请求，您不能重复提交";
                        return;
                    }
                    else
                    {
                        reader.Close();

                        //没有重复申请，检查是否已经加入，然后加入请求列表
                        //检查是否已经加入该工作组
                        queryString = "SELECT MemberID " +
                                      "FROM MembersOfGroups " +
                                      "WHERE MemberID = @userID AND GroupID = @GroupID";
                        command.CommandText = queryString;
                        command.Parameters.Clear();
                        command.Parameters.Add(userIDParameter);
                        command.Parameters.Add(GroupIDParameter);
                        try
                        {
                            reader = command.ExecuteReader();
                        }
                        catch (Exception exception)
                        {
                            notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER IN GROUP CHECK<br>" + exception.Message;                            
                            return;
                        }

                        if (reader.HasRows)
                        {
                            notification.InnerHtml = "您已经加入了小组 " + groupName_worked + " ,无需提出申请";
                            return;
                        }
                        else
                        {
                            reader.Close();

                            //没有加入工作组，至此通过所有检查，将申请提交至数据库
                            queryString = "INSERT INTO RequestList(GroupID, userID) " +
                                          "VALUES(@GroupID, @userID)";
                            command.CommandText = queryString;
                            command.Parameters.Clear();
                            command.Parameters.Add(userIDParameter);
                            command.Parameters.Add(GroupIDParameter);
                            try
                            {
                                command.ExecuteNonQuery();
                            }
                            catch (Exception exception)
                            {
                                notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER INSERT INTO RequestList<br>" + exception.Message;
                                return;
                            }

                            //执行成功，显示成功信息
                            dataBaseConnection.Close();
                            createGroup.InnerHtml = "您的申请已经成功提交！<br>" +
                                                    "请您耐心等待工作组的创建者的处理<br>" +
                                                    "<a href=\"welcome.aspx\">返回</a>";
                        }
                    }
                }
            }
        }
    }
}